<?php
/**
 * Created by PhpStorm.
 * User: AivyYuan
 * Date: 2016/7/12
 * Time: 16:20
 */
namespace app\models;

use yii\db\ActiveRecord;

class Blog extends ActiveRecord{
    public function rules()
    {
        return [
            [['title','category'],'required'],
            ['title','unique'],
            [['addtime','user_id'],'safe']
        ];
    }
    public function saveBlog($data){
        $content_model = new BlogContent();
        $tag_blog_model = new BlogTag();
        $tag_model = new Tags();

        $this->setAttributes($data);

        $content_model->setAttribute('content', $data['content']);
        if($this->validate() && $content_model->validate()){
            $blog_id = $this->insert();
            $content_model->blog_id = $this->id;
            $content_model->insert();
            $tag = isset($data['tags']) ? $data['tags'] :'';
            if($tag){
                $tags = explode(",",$tag );

                foreach ($tags as $v){

                    if($tag_row = Tags::findOne(['tag'=>$v])){
                        $tag_id = $tag_row->id;
                    }else{
                        $tag_model->tag = $v;
                        $tag_model->save();
                        $tag_id = $tag_model->id;
                    }

                    $tag_blog_model->tag_id = $tag_id;
                    $tag_blog_model->blog_id = $this->id;

                    $tag_blog_model->save();

                }
            }
            //保存tags
            return true;

        }else{
            $this->addErrors($content_model->errors);
            return false;
        }
    }
    public function getContent(){
        return $this->hasOne(BlogContent::className(),['blog_id'=>'id'] );
    }
    public function getUser(){
        return $this->hasOne(User::className(), ['id'=>'user_id']);
    }

    public function getFormattime(){
        return date("Y-m-d H:i:s",$this->addtime);
    }

}